/**
 * Date: 15-1-19
 */
define(["app", 'lodash',"directives/user/UserCard", "services/UserService",
        "resources/ChatResource", "resources/AddressResource", "resources/ContactsResource",
        'directives/InfiniteScroll', "directives/user/UserCard","directives/ScrollBar",
        "directives/common/OrgUserPicker",'directives/ColumnList'],
    function(app,_) {

        var deps = ["$scope","$window", "$state", "$stateParams", "$timeout", "UserService", "ChatResource", "AddressResource", "ContactsResource", "TipsService"];

        function controller($scope, $window, $state, $stateParams, $timeout, UserService, ChatResource, AddressResource, ContactsResource, TipsService) {
        	// 接收groupId 传给指令
        	$scope.currentOrgId = $stateParams.groupId;
        	$scope.currentUser = UserService.getCurrentUser();
        	
        	initParam($scope);
        	loadData($scope, AddressResource).success(function(){
        		$timeout(function(){calcWidth($scope.total);initHeight($timeout,$scope);},300);
        	});
        	initAction($scope, $window, $state, $timeout, ChatResource, AddressResource, ContactsResource);
        	$window.addEventListener('resize', _.throttle($scope.cal, 300));
        }
        
        function initAction($scope, $window, $state, $timeout, ChatResource, AddressResource, ContactsResource){
        	
        	$scope.cal = function(){
        		$scope.closePopup();
        		$timeout(function(){calcWidth($scope.total);initHeight($timeout,$scope);},300);
        	};
        	
        	/**
	         * 点击其他区域关闭弹出框
	         */
	        $scope.closePopup = function (event){
	        	$(".div-card-info").css("display","none"); 
	        };
	        
        	 //监控enter输入键触发搜索 一个是搜索组织 一个是搜索用户
            $scope.enterSearch = function($event){
        		if ($event.keyCode === 13) {
                    $scope.searchUser();
                }
            };
            
            $scope.$bus.subscribe({
	            channel: 'searchUser',
	            topic: 'searchUser',
	            callback: function () {
	            	$scope.searchUser();
	            }
	        });
            
            $scope.searchUser = function(){
            	$scope.data = [];
            	$scope.pages = {};
            	$scope.currentPage = 1;
                $scope.searchObj.searchKeyTemp = $scope.searchObj.searchKeyUser;
                loadData($scope, AddressResource).success(function(){
            		$timeout(function(){calcWidth($scope.total);initHeight($timeout,$scope);},300);
            	});
            };
            
            
	        /**
	         * 接收指令传过来的用户详细信息
	         */
	        $scope.setUser = function(userCard){
	        	$scope.user = userCard;
	        };
	        
	        $scope.changeUserOrg = function(flag){
	        	$timeout(function () {
	        		if (flag) { //显示
	        			var objDiv = $("#mydiv1"), position = objDiv.position(), len = 0;
						var top = objDiv.offset().top - objDiv.scrollParent().scrollTop();
						 
						var leng = 0;
						var userOrgList = $scope.user.userOrg;
						if(userOrgList && userOrgList.length < 4){
							leng = 40 * userOrgList.length;
						} else {
							leng = 170;
						}
						//判断超出
						if (top + objDiv.outerHeight() + leng > $(window).height()-76) {
							objDiv.css("top", position.top - leng + "px");
							$("#post").fadeOut(function(){
								$("#org").slideDown("slow");
							});
						}else{
							$("#post").fadeOut(function(){
								$("#org").slideDown("slow");
							});
						}
//						// @解决卡片过高引起滚动条
//						var minH = (Math.ceil($scope.data.length / Math.floor($(window).width() / (277 + 16 + 32)))) * (88 +12);
//		            	if(minH < objDiv.height()){
//		            		$(".groupList").css("min-height", objDiv.height() + 180);
//		            	}
	        		}else{
	        			$("#org").slideUp(function(){
	        				$("#post").fadeIn("slow");
	        			});
	        		}
	        	}, 300);
            };
            
	        /**
	         * 发起会话
	         */
	        $scope.selectSearch = function selectSearch(item) {
	        	var id = {};
	        	if (item.userId) {
	        		id.userId = item.userId;
                } else if (item.groupId) {
                	id.groupId = item.groupId;
                }
	        	// 会话页
	            ChatResource.query(id, null, 1).success(function (topic) {
	                $state.go('home.chat.msg', {
	                    id: topic.topicId
	                });
	            });
	        };
	        
	        $scope.gotoPage = function(number){
	        	$scope.currentPage = number;
	        	loadData($scope, AddressResource).success(function(){
	        		$timeout(function(){calcWidth($scope.total);initHeight($timeout,$scope);},300);
	        	});
	        };
        }
        
        function loadData($scope, AddressResource){
        	// loadTabs
        	$scope.loading = false;

            if ($scope.loading) {
                return;
            }
            $scope.loading = true;
            if(!$scope.searchObj.searchKeyTemp){
            	return AddressResource.queryOrgUsers($scope.currentOrgId, $scope.currentPage, $scope.pageSize).success(function(data){
    	        	generatePagesArray($scope, data.totalCount);
    	    		$scope.total = data.totalCount;
    	    		$scope.currentOrgName = data.fullName;
    	    		$scope.data = data.addressUserVoList;
    	        	$scope.loading = false;
    	        });
            }
            return AddressResource.queryUsers(null,  $scope.searchObj.searchKeyTemp, $scope.currentPage, $scope.pageSize).success(function(data){
            	generatePagesArray($scope, data.totalCount);
        		$scope.total = data.totalCount;
        		//$scope.currentOrgName = data.fullName;
        		$scope.data = data.addressUserVoList;
            	$scope.loading = false;
            });
        }
        
        /**
         * 分页计算设置
         */
        function generatePagesArray($scope, totalItems) {
            var maxBlocks, maxPage, maxPivotPages, minPage, numPages;
            maxBlocks = 11;
            $scope.pages = [];
            numPages = Math.ceil(totalItems / $scope.pageSize);
            if (numPages > 1) {
            	if($scope.currentPage != 1){
            		$scope.pages.push({
                        type: 'prev',
                        currentNum : $scope.currentPage,
                        number: Math.max(1, $scope.currentPage - 1),
                        active: $scope.currentPage > 1
                    });
            	}
            	$scope.pages.push({
                    type: 'first',
                    currentNum : $scope.currentPage,
                    number: 1,
                    active: $scope.currentPage > 1
                });
                maxPivotPages = Math.round((maxBlocks - 5) / 2);
                minPage = Math.max(2, $scope.currentPage - maxPivotPages);
                maxPage = Math.min(numPages - 1, $scope.currentPage + maxPivotPages * 2 - ($scope.currentPage - minPage));
                minPage = Math.max(2, minPage - (maxPivotPages * 2 - (maxPage - minPage)));
                var i = minPage;
                while (i <= maxPage) {
                    if ((i === minPage && i !== 2) || (i === maxPage && i !== numPages - 1)) {
                    	$scope.pages.push({
                            type: 'more',
                            active: false
                        });
                    } else {
                    	$scope.pages.push({
                            type: 'page',
                            number: i,
                            currentNum : $scope.currentPage,
                            active: $scope.currentPage !== i
                        });
                    }
                    i++;
                }
                $scope.pages.push({
                    type: 'last',
                    number: numPages,
                    currentNum : $scope.currentPage,
                    active: $scope.currentPage !== numPages
                });
                if($scope.currentPage < numPages){
                	$scope.pages.push({
                        type: 'next',
                        currentNum : $scope.currentPage,
                        number: Math.min(numPages, $scope.currentPage + 1),
                        active: $scope.currentPage < numPages
                    });
                }
            }
        };
        
        function calcWidth(total){
        	// nothing
        }
        
        function initHeight($timeout,$scope) {
        	$timeout(function(){
        		var target2 = $(".groupListHeight1"),
                offset2 = target2.offset();
        		if(angular.isDefined(offset2.top)){
        			target2.css("max-height", $(window).height()- offset2.top + 48);
        		}
            	var target4 = $(".groupList"),
                offset4 = target4.offset();
            	if ($scope.pages.length) { //有分页
            		target4.css("min-height", $(window).height()- offset4.top - 76);
            	} else {
            		target4.css("min-height", $(window).height()- offset4.top);
            	}
        	},888);
        }
        
        function initParam($scope){
        	
        	$scope.page = {}; // 分页
            $scope.searchObj = {};
            
        	$scope.data = [];
    		$scope.currentPage = 1;
    		$scope.pageSize = 24;
    		$scope.search = {};
    		$scope.search.key = null;
    		
        }
        
        controller.$inject = deps;
        app.lazy.controller("UserListController", controller);
    });

